
import sys
import os
import cv2

class CharFrame:
    ascii_char="!@#$%^&*#$%^&*@#$%^&*(#$%^&*()#$%^&*(#$%^&*(#$%^&*()@#$%^&*()_"

    #像素映射到字符

    def pixelToChar(self, luminance):
        return self.ascii_char[int(luminance/256*len(self.ascii_char))]
        # 转化为ascii字符

    def convert(self, img, limitSize=-1, fill=False, wrap=False):
        if limitSize !=-1 and (img.shape[0]> limitSize[1] or img.shape[1]> limitSize[0]):
            img = cv2.resize(img, limitSize, interpolation=cv2.INTER_AREA)
        print (img,'______________________')
        ascii_frame=''
        blank=''

        if fill:
            blank += ''*(limitSize[0]-img.shape[1])
        if wrap:
            blank += '\n'
        for i in range (img.shape[0]):
            # shape 为元组 图片的（宽，高）
            for j in range (img.shape[1]):
                ascii_frame += self.pixelToChar(img[i,j])
            ascii_frame += blank
        return ascii_frame

#class V2Char (CharFrame):

class I2Char(CharFrame):
    result = None
    def __init__(self, path ,limitSize=-1, fill=False, wrap=False):
        self.genCharImage(path, limitSize, fill, wrap)

    def genCharImage (self, path, limitSize=-1, fill= False, wrap=False):

        #调用CharFrame父类的convert方法，传入path路径参数

# 将图片转化为数组的形式
        img = cv2.imread(path, cv2.iread_grayscale)
        # 转为灰度图片

        frame=self.convert(img, os.get_terminal_size(), fill=True)
        #获取terminal 界面尺寸
        self.result = frame

    def show (self, stream=2):
        if self.result is None:
            return
        if stream ==1 and os.isatty(sys.stdout.fileno()):
            self.streamOut = sys.stdout.write
            self.streamFlush = sys.stdout.flush
        elif stream ==2 and os.isatty(sys.stdout.fileno()):
            self.streamOut = sys.stdout.write
            self.streamFlush = sys.stdout.flush
        elif hasattr(stream, 'write'):
            self.streamOut = sys.stdout.write
            self.streamFlush = sys.stdout.flush
        self.streamOut(self.result)
        self.streamFlush()
        self.streamOut('\n')

if _name_=='_main_':

    import argparse
    # 命令行输入参数

    parser= argparse.ArgumentParser()
    parser.add_argument('file', help='Image file, .jpeg or .png')
    #输入文件

#获取参数
    args = parser.parse_args()

    # 实例化 I2Char 类对象为i2char， 实例化初始化参数直接调用genCharImage生成字符画

    i2char = I2Char (args.file)

#terminal 打印字符画
    i2char.show()






